﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using micsun.Logic;
using micsun;
using micsun.Logic.Security;
using micsun.Web;
using Typhone.Public.Security;

namespace tmsWeb 
{
    public partial class Logon : NonSecurityPage
    {
        protected override bool AllowScroll
        {
            get
            {
                return false;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ReturnUrl = Request.Params["rui"];
            }
            catch
            {
            }
        }

        static Logon()
        {
            _userList = new CaseInsensitiveCollection();
        }
        protected string ReturnUrl;
        static CaseInsensitiveCollection _userList;
        protected void btnLogon_Click(object sender, ImageClickEventArgs e)
        {
           
            UserIdentity user = new UserIdentity(tbID.Text, -1, UserType.BackUser);

            if (!user.ValidatePassword(tbPwd.Text))
            {
                AddMessage("密码错误！");
                SystemLog.WriteWarning("logon", "IP:" + Request.UserHostAddress + "登陆失败!");
                return;
            }
            string HostName = Request.UserHostName;
            if (!(ConfigurationManager.AppSettings.Get("MultLogin") == "true") && _userList.Contains(tbID.Text) && _userList[tbID.Text].ToString() != HostName)
            {
                AddMessage("用户已经登陆！");
                return;
            }

            SiteSecurity.Instance.Logon(user, Session);

            if (!_userList.Contains(tbID.Text))
            {
                _userList.Add(tbID.Text, HostName);

            }
            
            if (ReturnUrl != null && ReturnUrl != string.Empty)
            {
                Transfer.Redirect(ReturnUrl, false);
            }
            else
            {

                Transfer.RedirectToNamedPage("home");
            }
        }

        public static void RemoveUser(System.Web.SessionState.HttpSessionState session)
        {
            IUserIdentity user = SiteSecurity.Instance.GetUser(session);
            if (user!=null)
            {
                commfuncs.Search.SearchBL.DropLastTempHeapTable(user.LastTempTable);
            }
            if (user != null)
                Typhone.Public.Public.Common.RecordLock.UnLockAll(user);
            if (user != null)
                lock (typeof(Logon))
                    _userList.Remove(user.ID);
        }

        public static void RemoveUser()
        {
            RemoveUser(HttpContext.Current.Session);
        }
    }
}
